import fs from '@ohos.file.fs';
import { Context } from '@ohos.abilityAccessCtrl';

let unitArray = [`B`, 'KB', 'MB', "GB"];

export class FileUtil {
  static sizeString(size: number): string {
    let index = 0;
    let n = size;
    while (1) {
      if (n > 1024) {
        index++;
        n = n / 1024;
      }
      else {
        break;
      }
    }
    return `${n.toFixed(2)}${unitArray[index]}`
  }


  static documentToCache(context: Context, arr: Array<string>): string[] {
    // if (arr == null) {
    //   return null;
    // }
    // var caches = new Array<string>(arr.length);
    // for (let i = 0;i < arr.length; i++) {
    //   caches[i] = FileUtil.uriToFile(context, arr[i])
    // }
    // return caches;
    return []
  }


  /**
   * 将文件从系统选择器返回的uri,拷贝到app内部的目录返回其路径.
   * @param context
   * @param uriPath
   * @returns
   */
  static uriToFile(context: Context, uriPath: string): string {
    // let filesDir = context.filesDir;
    // // file://cn.coremail.hwmail/data/storage/el2/base/haps/tablet/files/1.png
    // let dir = `MailCache`
    // try {
    //   dir = this.mkdirRecursivelyIfNeeded(filesDir, dir);
    // }
    // catch (e) {
    //   console.log(e)
    // }
    // var timestamp = Date.parse(new Date().toString());
    // let filePath = `${dir}` + uriPath.substring(uriPath.lastIndexOf("/"), uriPath.length);
    // try {
    //   // var fileStat = await fs.stat(uriPath);
    //   // let buffer = new ArrayBuffer(fileStat.size > 4096 ? 4096 : fileStat.size);
    //   let buffer = new ArrayBuffer(4096);
    //   let readFile = fs.openSync(uriPath, fs.OpenMode.READ_ONLY);
    //   let readLen = fs.readSync(readFile.fd, buffer, { offset: 0, length: 4096 });
    //
    //   var offset = 0;
    //
    //   let writeFile = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
    //   while (readLen > 0) {
    //     fs.writeSync(writeFile.fd, buffer);
    //     offset += readLen;
    //     readLen = fs.readSync(readFile.fd, buffer, { offset: offset, length: 4096 });
    //   }
    //   fs.closeSync(readFile);
    //   fs.closeSync(writeFile);
    //   return filePath;
    // }
    // catch (e) {
    //   console.log(e)
    // }
    return "";
  }


  static mkdirRecursivelyIfNeeded(rootDir: string, newDirPath: string): string {
    let pathComponents = newDirPath.split('/');
    let dir = `${rootDir}`
    for (let i = 0; i < pathComponents.length; i++) {
      let component = pathComponents[i];
      dir += `/${component}`
      if (fs.accessSync(dir)) {
        continue
      }
      else {
        fs.mkdirSync(dir);
      }
    }
    return dir;
  }
}